import { API } from '@/services';
import type { InputLogin, Token } from '@/services/users/types';
import { Role } from '@/services/users/types';
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTokenStore = defineStore('token', ()  => {
  const token = ref<Token>({
    token: '',
    role: Role.Student,
    id: 0,
  });
  const isLogin = ref<boolean>(false);

  function getRole() {
    return token.value.role;
  }

  async function dispatchLogin (input: InputLogin) {
    await API.users.login(input).then((res) => {
      console.log(res);
      if (res.status === 200) {
        console.log(res.data.role);
        let role = Role.Student;
        switch (res.data.role) {
          case 'student': role = Role.Student; break;
          case 'teacher': role = Role.Teacher; break;
          case 'admin': role = Role.Admin; break;
        }
        token.value = {
          token: res.data.token,
          role: role,
          id: res.data.id,
        };
        isLogin.value = true;
      }
    }).catch((err) => {
      if (err.response.status === 400) {
        throw new Error('用户名或密码错误');
      } else if (err.request) {
        throw new Error('网络错误');
      }
    });

  }

  return {
    token,
    getRole,
    isLogin,
    dispatchLogin,
  }
});
